import React, { useState, useEffect } from 'react'
import './TabStyle.css'

interface ItemType {
  label: string
  value: string
  num?: number
}

interface Props {
  list: ItemType[]
  title: string
  activeTab: string
  onChangeTab: (item: ItemType) => void
}

const TabList: React.FC<Props> = ({ list, title, activeTab, onChangeTab }) => {
  const [activeTabIndex, setActiveTabIndex] = useState<number | null>(null)

  useEffect(() => {
    if (list.length > 0) {
      const initialActiveItem = list.find((item) => item.value === activeTab)
      if (initialActiveItem) {
        setActiveTabIndex(list.indexOf(initialActiveItem))
      } else {
        setActiveTabIndex(0)
      }
    }
  }, [list, activeTab])

  const handleTabClick = (item: ItemType) => {
    onChangeTab(item)
  }

  return (
    <div className="tab-wrapper tab-list-style">
      {title && <span className="tab-item">{title}：</span>}
      <div>
        {list.map((item, index) => (
          <span
            key={item.value}
            className={`tab-item margins pointer ${activeTabIndex === index ? 'active' : ''}`}
            onClick={() => handleTabClick(item)}>
            <span>{item.label}</span>
            {'·'}
            {item.num && <span>{item.num}</span>}
          </span>
        ))}
      </div>
    </div>
  )
}

export default TabList
